package net.bat.web.xggrzl;

import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import net.bat.entity.User;
import net.bat.service.account.ShiroDbRealm.ShiroUser;

@Controller
@RequestMapping(value = "/updateinfo")
public class UpadtePersonController {
	@Autowired
	private UpdatePersonService ups;
	
	@RequestMapping(method = RequestMethod.GET)
	public String updateForm(Model model) {
		Long id = getCurrentUserId();
		model.addAttribute("user", ups.getUser(id));
		return "personinfo/updateinfo";
	}
	@RequestMapping(method = RequestMethod.POST)
	public String update(@Valid @ModelAttribute("user") User user) {
		ups.updateUserInfo(user);
		return "personinfo/success";
		}

	
	@ModelAttribute
	public void getUser(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		if (id != -1) {
			model.addAttribute("user", ups.getUser(id));
		}
	}
	private Long getCurrentUserId() {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		return user.id;
		
	}

	
	@RequestMapping(value = "/checkPassword")
	@ResponseBody
	public String checkLoginName(String orgPassword) {
		Long id = getCurrentUserId();
		User user=ups.getUser(id);
		String salt=user.getSalt();
		String password=user.getPassword();
		
		if (ups.checkPassword(orgPassword,salt).equals(password)) {
			System.out.println("密码匹配成功");
			return "true";
		} else {
			System.out.println("密码匹配失败");
			return "false";
		}
	}
	
}
